package com.example.demo.controller;

import com.example.demo.domain.Result;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import com.example.demo.domain.UserDb;
import com.example.demo.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by Administrator on 2017/7/6.
 */
@RestController
public class UserController {

    private final static Logger logger= LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户的信息
     * @return
     */
    @GetMapping(value = "/user")
    public List<UserDb> userList(){
        logger.info("getList");
        return userRepository.findAll();
    }

    /**
     * 新增
     * @param userDb
     * @param bindingResult
     * @return
     */
    @PostMapping(value = "/user")
    public Result userAdd(@Valid UserDb userDb, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
//            return bindingResult.getFieldError().getDefaultMessage();

            return ResultUtil.error(-1,bindingResult.getFieldError().getDefaultMessage());
        }
        userDb.setAge(userDb.getAge());
        userDb.setName(userDb.getName());
        return ResultUtil.success(userRepository.save(userDb));
    }

    /**
     * 查询用户
     * @param id
     * @return
     */
    @GetMapping(value = "/user/{id}")
    public UserDb userFind(@PathVariable("id") Integer id){
        return userRepository.findOne(id);
    }

    /**
     * 更新用户
     * @param id
     * @param age
     * @param name
     * @return
     */
    @PutMapping(value = "/user/{id}")
    public UserDb userUpdate(@PathVariable("id") Integer id,@RequestParam("age") Integer age,@RequestParam("name") String name){
        UserDb userDb=new UserDb();
        userDb.setId(id);
        userDb.setAge(age);
        userDb.setName(name);
        return userRepository.save(userDb);
    }

    /**
     * 删除
     * @param id
     */
    @DeleteMapping(value = "/user/{id}")
    public void userDelete(@PathVariable("id") Integer id){
        userRepository.delete(id);
    }

    @GetMapping(value = "/user/age/{age}")
    public List<UserDb> getListByAge(@PathVariable("age") Integer age){
        return userRepository.findByAge(age);
    }

    @PostMapping(value = "/user/two")
    public void userTwo(){
        userService.insertTwo();
    }

    @GetMapping(value = "user/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        userService.getAge(id);
    }
}
